package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.ConversationActivity.NotifyActivity;
import com.srwl.mytx.activity.WithdrawActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 提现通知通知适配器
 * <p>
 */
public class TransferNotifyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "TransferNotifyAdapter";
    private Context context;
    private List<Message> messageList;
    private NotifyMessageInteractionListener listener;


    public TransferNotifyAdapter(Context context, List<Message> messageList, NotifyMessageInteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //手动处理提现订单的通知消展示
        View transferView = LayoutInflater.from(context).inflate(R.layout.notify_message_transfer_item_layout, parent, false);
        return new TransferHolder(transferView);


    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        Message notify = messageList.get(position);
        TransferHolder viewHolder = (TransferHolder) holder;
        Transfer transfer = JSONObject.parseObject(notify.getExtraData(), Transfer.class);//提现信息
        User targetUser = transfer.getTargetUser();
        //Glide.with(context).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(viewHolder.iv_avatar);
        GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), viewHolder.iv_avatar, R.drawable.tx_default_avatar_1);
        viewHolder.tv_username.setText(targetUser.getUsername());
        viewHolder.tv_amount.setText(Utils.moneyFormat(transfer.getAmount()));
        viewHolder.tv_account.setText(transfer.getAliAccount());
        viewHolder.tv_apply_time.setText(DateUtils.getTimestampString(transfer.getCreateDate()));
        viewHolder.tv_contact.setOnClickListener(v -> contact(transfer.getuId()));
        viewHolder.iv_avatar.setOnClickListener(v -> contact(transfer.getuId()));
        viewHolder.itemView.setOnClickListener(v -> toTransferDetail(transfer));
        switch (transfer.getStatus()) {

            case Constant.ORDER_TRANSFER_APPLY_STATUS:
                viewHolder.tv_transfer_status.setText("用户申请提现,请尽快处理");
                break;
            case Constant.ORDER_TRANSFER_SUCCESS_STATUS:
                viewHolder.tv_transfer_status.setText("已经处理,用户提现成功");
                break;
            case Constant.ORDER_TRANSFER_ERROR_STATUS:
                viewHolder.tv_transfer_status.setText("异常提现订单");
        }

    }


    /**
     * 跳转到提现订单详情
     *
     * @param transfer
     */
    private void toTransferDetail(Transfer transfer) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        intent.putExtra(Constant.EXTRA_INFO_TRANSFER, transfer);
        intent.putExtra("getTaskInfo", true);
        ((Activity) context).startActivityForResult(intent, NotifyActivity.REQUEST_CODE_TO_TRANSFER_DETAIL);
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }


    public class TransferHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_username)
        TextView tv_username;
        @BindView(R.id.tv_amount)
        TextView tv_amount;
        @BindView(R.id.tv_account)
        TextView tv_account;
        @BindView(R.id.tv_apply_time)
        TextView tv_apply_time;
        @BindView(R.id.tv_transfer_status)
        TextView tv_transfer_status;
        @BindView(R.id.tv_contact)
        TextView tv_contact;

        public TransferHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
        } else {
            getFullUserInfo(targetUserId);
        }
    }


    private void getFullUserInfo(String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }


}
